package com.zxc.elasticsearch;

import com.alibaba.fastjson.JSON;
import com.zxc.elasticsearch.mapper.ApArticleMapper;
import com.heima.model.search.pojos.SearchArticleVo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@SpringBootTest(classes = ElasticsearchApplication.class)
@RunWith(SpringRunner.class)
public class esInit {

    @Resource
    private ApArticleMapper apArticleMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    public void init() throws Exception {
        List<SearchArticleVo> searchArticleVos = apArticleMapper.loadArticleList();
        BulkRequest bulkRequest = new BulkRequest("app_info_article");


        for (SearchArticleVo searchArticleVo : searchArticleVos) {
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(searchArticleVo.getId().toString());
            indexRequest.source(JSON.toJSONString(searchArticleVo), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
    }
}
